package com.ycy.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.LinkedList;
import java.util.List;

public class NewIO {

  //解决了c10k问题
  public static void main(String[] args) {

    //com.ycy.nio 实现
    try {
      List<SocketChannel> list = new LinkedList<>();
      ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
      serverSocketChannel.bind(new InetSocketAddress(8090));
      //设置服务端非阻塞
      serverSocketChannel.configureBlocking(false);

      while (true) {
        try {
          Thread.sleep(1000);
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
        //accept 非阻塞 socketChannel 会为一个连接新建一个 fd
        SocketChannel socketChannel = serverSocketChannel.accept();
        if (socketChannel == null) continue;
        //设置客户端 非阻塞
        socketChannel.configureBlocking(false);

        SocketAddress remoteAddress = socketChannel.getRemoteAddress();
        System.out.println(remoteAddress);
        list.add(socketChannel);
        for (SocketChannel socketChannelelement : list) {
          ByteBuffer buf = ByteBuffer.allocateDirect(1024);
          // 非 阻塞 类似 rec()
          int read = socketChannelelement.read(buf);
          if (read > 0) {
            buf.flip();
            byte[] aaa = new byte[buf.limit()];
            // 把buffer赋值给数组
            buf.get(aaa);
            System.out.println(new String(aaa));

          }

        }
      }


    } catch (IOException e) {
      e.printStackTrace();
    }

  }

}
